package com.photoeditor.demo.util;

import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.Matrix;
import android.graphics.Paint;
import android.graphics.Rect;

import com.common.base.utils.DebugUtil;
import com.photoeditor.demo.model.image.util.ImageHelper;

import java.io.File;

import static com.photoeditor.demo.model.face.FaceConstant.PATH_PHOTO;



public class BitmapUtil {

    private final static int HEIGHT_LIMIT = 500;
    public static String getOptimizeBmpBase64(Bitmap src) {
        try {
            int width = (int) src.getWidth();
            int height = (int) src.getHeight();
            Bitmap tmpRes = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_4444);

            Canvas canvas = new Canvas(tmpRes);
            Paint paint = new Paint(Paint.ANTI_ALIAS_FLAG);

            Rect faceYou = new Rect(0, 0, width, height);
            Rect youDst = new Rect(0, 0, width, height);
            canvas.drawBitmap(src, faceYou, youDst, paint);

            Bitmap resizedBmp = null;
            //缩放Bitmap
            if (height > HEIGHT_LIMIT) {
                float mOptimizeSizeRatio = HEIGHT_LIMIT * 1f / height;
                Matrix matrix = new Matrix();
                matrix.setScale(mOptimizeSizeRatio, mOptimizeSizeRatio);
                resizedBmp = Bitmap.createBitmap(tmpRes, 0, 0, tmpRes.getWidth(), tmpRes.getHeight(), matrix, true);
            }

            //质量压缩至小于50kb
            Bitmap resBmp = ImageHelper.compressJpgToLimitKB(resizedBmp != null ? resizedBmp : tmpRes, 50);
            if (resBmp == null) return null;

            if (DebugUtil.isDebuggable()) {
                String tmpPath = PATH_PHOTO + File.separator + System.currentTimeMillis() + "_optimized_single.jpg";
                ImageHelper.saveBitmapToSdcard(tmpPath, resBmp);
            }
            String base64 = ImageHelper.bitmapToBase64(resBmp);

            if (tmpRes != null && !tmpRes.isRecycled()) tmpRes.recycle();
            if (resizedBmp != null && !resizedBmp.isRecycled()) resizedBmp.recycle();
            if (resBmp != null && !resBmp.isRecycled()) resBmp.recycle();

            return base64;
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }
}
